package org.soarsky.wealthchengdu.module.home;

import java.io.File;
import java.sql.Date;
import java.text.SimpleDateFormat;

import m.framework.ui.SlidingMenu;

import org.soarsky.wealthchengdu.R;
import org.soarsky.wealthchengdu.appliction.MyAppliction;
import org.soarsky.wealthchengdu.db.DBtool;
import org.soarsky.wealthchengdu.entity.JsonResult;
import org.soarsky.wealthchengdu.entity.LogonResult;
import org.soarsky.wealthchengdu.entity.NewsContentData;
import org.soarsky.wealthchengdu.imageCache.CacheMemUtil;
import org.soarsky.wealthchengdu.imageCache.ImageLoader;
import org.soarsky.wealthchengdu.imageCache.ImageLoader.ImageCallback;
import org.soarsky.wealthchengdu.module.comment.CommentActivity;
import org.soarsky.wealthchengdu.module.focus.FocusActivity;
import org.soarsky.wealthchengdu.network.ParserResults;
import org.soarsky.wealthchengdu.share.ShareAllGird;
import org.soarsky.wealthchengdu.util.Config;
import org.soarsky.wealthchengdu.view.ALLSendDialog;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.framework.AbstractWeibo;

public class HomeDetailsActivity extends Activity {
	ImageView focus_iv_one, focus_iv_two, focus_iv_three, focus_iv_four;
	ImageView titleReturn;
	TextView titleText;
	NewsContentData newscontentdata;
	ParserResults service;
	WebView homeWebView;
	String intent;
	private PopupWindow mPopupWindow;
	private static SlidingMenu menu;
	String fenx;
	String imgUrl;
	TextView textName, textDate, textBaoshe, textOne, textTwo, textThree,
			textFour;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_focus);
		service = new ParserResults();
		intnView();
		intent = getIntent().getStringExtra("gNumber");
		Log.e("ss", intent + "zzzzzzzzzzzzzzzzzz");

		loadData(homeWebView);
		ALLSendDialog.showdialog(this);
		titleReturn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				HomeDetailsActivity.this.finish();
			}
		});

		focus_iv_one.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				focus_iv_one.setImageResource(R.xml.praise);
				String s = MyAppliction.ID;
				try {
//					 JsonResult<String> jsonResult = service
//					 .sendVote(MyAppliction.ID);
					 loadDatas();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		});
		focus_iv_two.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				focus_iv_two.setImageResource(R.xml.comment);
				Intent intent = new Intent(HomeDetailsActivity.this,
						CommentActivity.class);
				startActivity(intent);
			}
		});
		focus_iv_three.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				initPopupWindow();
				showPopupWindow(focus_iv_three);
				focus_iv_three.setImageResource(R.xml.collect);
				DBtool.getDBTool(HomeDetailsActivity.this).insertData(
						newscontentdata);

			}
		});
		focus_iv_four.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String path = CacheMemUtil.getImagePath(imgUrl);
				if (new File(path).exists()) {
					showGrid(true);
				} else {
					Toast.makeText(HomeDetailsActivity.this,
							"正在获取图片信息，请稍后分享...", 500).show();
				}

			}
		});

	}

	// 使用快捷分享完成图文分享
	private void showGrid(boolean silent) {
		Intent i = new Intent(menu.getContext(), ShareAllGird.class);
		// 分享时Notification的图标
		i.putExtra("notif_icon", R.drawable.ic_launcher);
		// 分享时Notification的标题
		i.putExtra("notif_title", menu.getContext()
				.getString(R.string.app_name));
		// address是接收人地址，仅在信息和邮件使用，否则可以不提供
		i.putExtra("address", "12345678901");
		// title标题，在印象笔记、邮箱、信息、微信（包括好友和朋友圈）、人人网和QQ空间使用，否则可以不提供
		i.putExtra("title", menu.getContext().getString(R.string.share));
		/** 这个自己的分享标题 */
		// titleUrl是标题的网络链接，仅在QQ空间使用，否则可以不提供
		i.putExtra("titleUrl", "http://sharesdk.cn");
		// text是分享文本，所有平台都需要这个字段
		i.putExtra("text", fenx);
		/** 这个自己输入分享内容 */
		// imagePath是本地的图片路径，在豆瓣、Facebook、网易微博、新浪微博、腾讯微博、Twitter、邮箱、
		// 信息和微信（包括好友和朋友圈）图片分享中使用，否则可以不提供
		// i.putExtra("imagePath", "/mnt/sdcard/as.png");
		i.putExtra("imagePath", CacheMemUtil.getImagePath(imgUrl));
		// Log.e("ss",
		// CacheMemUtil.getImagePath(imgUrl)+"`````````````````````````");
		// CacheMemUtil.getImagePath(imgUrl)
		// imageUrl是网络的图片路径，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("imageUrl",
				"http://sharesdk.cn/Public/Frontend/images/logo.png");
		// url仅在人人网和微信（包括好友和朋友圈）中使用，否则可以不提供
		i.putExtra("url", "http://sharesdk.cn");
		// thumbPath是缩略图的本地路径，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
		//i.putExtra("thumbPath", CacheMemUtil.getImagePath(imgUrl));
		// appPath是待分享应用程序的本地路劲，仅在微信（包括好友和朋友圈）中使用，否则可以不提供
        //	i.putExtra("appPath", FocusActivity.TEST_IMAGE);
		// comment是我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		i.putExtra("comment", menu.getContext().getString(R.string.share));
		// site是分享此内容的网站名称，仅在QQ空间使用，否则可以不提供
		i.putExtra("site", menu.getContext().getString(R.string.app_name));
		// siteUrl是分享此内容的网站地址，仅在QQ空间使用，否则可以不提供
		i.putExtra("siteUrl", "http://sharesdk.cn");

		// 是否直接分享
		i.putExtra("silent", silent);
		menu.getContext().startActivity(i);
	}

	private void showPopupWindow(View view) {
		if (!mPopupWindow.isShowing()) {
			// mPopupWindow.showAsDropDown(view,0,0);
			mPopupWindow.showAtLocation(view, Gravity.CENTER, 100, 430);
		}
	}

	public void intnView() {
		Log.e("ggggg", "ggggggggggggggggggggggggggggggg");
		newscontentdata = new NewsContentData();
		menu = new SlidingMenu(HomeDetailsActivity.this);
		AbstractWeibo.initSDK(HomeDetailsActivity.this);
		homeWebView = (WebView) findViewById(R.id.focus_webview);
		titleReturn = (ImageView) findViewById(R.id.title_iv_img);
		titleText = (TextView) findViewById(R.id.title_tv_text);

		focus_iv_one = (ImageView) findViewById(R.id.focus_iv_one);
		focus_iv_two = (ImageView) findViewById(R.id.focus_iv_two);
		focus_iv_three = (ImageView) findViewById(R.id.focus_iv_three);
		focus_iv_four = (ImageView) findViewById(R.id.focus_iv_four);

		textName = (TextView) findViewById(R.id.focus_tv_name);
		textDate = (TextView) findViewById(R.id.focus_day);
		textBaoshe = (TextView) findViewById(R.id.focus_off);
		textOne = (TextView) findViewById(R.id.cd_tv_zan);
		textTwo = (TextView) findViewById(R.id.cd_tv_chat);
		textThree = (TextView) findViewById(R.id.cd_tv_collectss);
		textFour = (TextView) findViewById(R.id.cd_tv_share);
	}
	
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		Log.e("ggggg", "start~~~");
		super.onStart();
	}

	private void loadData(final WebView webView) {
		new AsyncTask<Void, Void, Boolean>() {

			@Override
			protected Boolean doInBackground(Void... params) {
				// TODO Auto-generated method stub
				getLogon();
				try {
					JsonResult<NewsContentData> result = service
							.getNewsContent(intent);
					if (result == null)
						return false;
					if (result.isError()) {
						error(result);
						// 错误处理
						return false;
					} else {
						NewsContentData dataMsg = result.getData();
						if (dataMsg != null) {// 判断是否有数据
							newscontentdata = dataMsg;
							return true;
						}
						// Log.e("ss", "set111111111111111111");
						// Log.e("ss", newscontentdata.getSubTitle()+"1");
						// Log.e("ss", newscontentdata.getAddTime()+"2");
						// Log.e("ss", newscontentdata.getAgenda()+"3");
						// Log.e("ss", newscontentdata.getCateId1()+"4");
						// Log.e("ss", newscontentdata.getCollectNum()+"5");
						// Log.e("ss", newscontentdata.getImg()+"6");
						// Log.e("ss", newscontentdata.getSource()+"7");
						// imgUrl=newscontentdata.getImg();
						// Log.e("ss", newscontentdata.getTitle()+"8");
						// Log.e("ss", newscontentdata.getContent()+"8");
						//
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
				}
				return false;
			}

			protected void onPostExecute(Boolean result) {
				// UI更新操作
				if (result) {
					setwebview(webView);
					if (MyAppliction.mCn == 0) {
						fenx = newscontentdata.getSource() + ":"+ newscontentdata.getTitle();
						textName.setText(newscontentdata.getTitle());
						textDate.setText(getStrTime(newscontentdata
								.getAddTime()));
						textBaoshe.setText(newscontentdata.getAgenda());
						textOne.setText(newscontentdata.getAdmireNum());
						textTwo.setText(newscontentdata.getRemarkNum());
						textThree.setText(newscontentdata.getCollectNum());
						textFour.setText(newscontentdata.getShareNum());
					} else {
						fenx = newscontentdata.getSourceEn() + ":"
								+ newscontentdata.getTitleEn();
						textName.setText(newscontentdata.getTitleEn());
						textDate.setText(getStrTime(newscontentdata
								.getAddTime()));
						textBaoshe.setText(newscontentdata.getAgendaEn());
						textOne.setText(newscontentdata.getAdmireNum());
						textTwo.setText(newscontentdata.getRemarkNum());
						textThree.setText(newscontentdata.getCollectNum());
						textFour.setText(newscontentdata.getShareNum());
					}
					imgUrl = newscontentdata.getImgEn();
					loadImage(imgUrl);
					String map = CacheMemUtil.getImagePath(imgUrl);
					Bitmap map1 = CacheMemUtil.getImageFromCache(imgUrl);
					Log.e("ss", imgUrl + "`````````````````````````");
					Log.e("ss", CacheMemUtil.getImagePath(imgUrl)
							+ "`````````````````````````");
					// CacheMemUtil.getImageFromCache(imgUrl);
				} else {

				}

			};
		}.execute();
	}

	
	private void loadDatas() {
	new AsyncTask<Void, Void, Boolean>() {

		@Override
		protected Boolean doInBackground(Void... params) {
			// TODO Auto-generated method stub
			getLogon();
			try {
				JsonResult<String> jsonResult = service .sendVote(MyAppliction.ID);
				if (jsonResult == null)
					return false;
				if (jsonResult.isError()) {
					error(jsonResult);
					// 错误处理
					return false;
				} 
			} catch (Exception e) {
				// TODO Auto-generated catch block
			}
			return false;
		}

		protected void onPostExecute(Boolean result) {
			// UI更新操作
			if (result) {
			
				
				// CacheMemUtil.getImageFromCache(imgUrl);
			} else {

			}

		};
	}.execute();
}
	
	
	
	
	
	private void loadImage(final String url) {

		// Bitmap bm = CacheMemUtil.getImage(url);
		Bitmap bm = CacheMemUtil.getImageFromCache(url); // 第一步，仅仅只从内存中读取
		if (bm != null) {
			// 包括从本地获取的，未进行图片处理的图片
			// bm = ImageUtil.zoomBitmap(bm, iconWidth, iconHeight);// 缩放处理
			// bm = ImageUtil.getRoundedCornerBitmap(bm, corners);// 圆角处理
			// CacheMemUtil.putImage2Cache(url, bm);

		} else {

			ImageLoader.getInstance().loadBitmap(url, new ImageCallback() {

				public void imageLoaded(Bitmap bm) {
					if (bm != null) {
						// //以下两行，根本不该在这里调用，应该在存在本地之前，而不是读取显示时才做处理
						// bm = ImageUtil.zoomBitmap(bm, iconWidth,
						// iconHeight);// 缩放处理
						// bm = ImageUtil.getRoundedCornerBitmap(bm, corners);//
						// 圆角处理
						CacheMemUtil.putImage2Cache(url, bm);
						// image.setImageBitmap(bm); //不能使用这句方法，否则会在加载完之前错误显示
					}
				}
			});
		}

	}

	// 将时间戳转为字符串
	public static String getStrTime(String cc_time) {
		String re_StrTime = null;
		SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
		// 例如：cc_time=1291778220
		long lcc_time = Long.valueOf(cc_time);
		re_StrTime = sdf.format(new Date(lcc_time * 1000L));
		return re_StrTime;
	}

	// 必须先登录
	private void getLogon() {
		try {
			JsonResult<LogonResult> jsonResult = service.authLogon("张三");
			if (jsonResult != null) {
				if (jsonResult.isError()) {
					error(jsonResult);
				} else {// 登录成功
					System.out.println(jsonResult.getData().getUserId() + "==="
							+ jsonResult.getData().getNickName());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.toString() + "===");
		}
	}

	private static void error(JsonResult<?> jsonResult) {
		System.out.println("错误码:" + jsonResult.getCode() + "===错误信息:"
				+ jsonResult.getMsg());
	}

	public void setwebview(WebView webview) {
		if (newscontentdata != null) {
			if (MyAppliction.mCn == 0) {
				webview.loadDataWithBaseURL(null, MyAppliction.htmlhead
						+ newscontentdata.getContent() + MyAppliction.htmlhead,
						"text/html", "utf-8", null);
				webview.setWebChromeClient(new MyWebChromeClient());
				// webview.setWebViewClient(new WebViewClient()
				// {
				// @Override
				// public void onPageFinished(WebView view,String url)
				// {
				// ALLSendDialog.dimssdialog();
				// }
				// });
			} else {
				webview.loadDataWithBaseURL(null,
						newscontentdata.getContentEn(), "text/html", "utf-8",
						null);
				webview.setWebChromeClient(new MyWebChromeClient());
				// webview.setWebViewClient(new WebViewClient()
				// {
				// @Override
				// public void onPageFinished(WebView view,String url)
				// {
				// ALLSendDialog.dimssdialog();
				// }
				// });
			}
		} else {
			Toast.makeText(this,
					Config.changeLanguage(MyAppliction.mChoose).getNodata(),
					Toast.LENGTH_LONG).show();
		}
	}

	class MyWebChromeClient extends WebChromeClient {
		@Override
		public void onProgressChanged(WebView view, int newProgress) {
			// TODO Auto-generated method stub
			// 查看加载进度
			Log.e("the load", "~~~~~~~~progress:" + newProgress); // //////////
			// 加载完毕
			if (newProgress == 100) {
				ALLSendDialog.dimssdialog();
			}
			super.onProgressChanged(view, newProgress);
		}

	}

	private void initPopupWindow() {
		View view = LayoutInflater.from(HomeDetailsActivity.this).inflate(
				R.layout.popupwindow, null);

		mPopupWindow = new PopupWindow(view, LayoutParams.WRAP_CONTENT,
				LayoutParams.WRAP_CONTENT);
		// mPopupWindow.setBackgroundDrawable(new
		// BitmapDrawable());//必须设置background才能消失
		mPopupWindow.setBackgroundDrawable(HomeDetailsActivity.this
				.getResources().getDrawable(R.drawable.popuwindow));
		mPopupWindow.setOutsideTouchable(true);
		TextView textView = (TextView) view.findViewById(R.id.popuwindow_text);
		textView.setText("收藏成功");
		// 自定义动画
		// mPopupWindow.setAnimationStyle(R.style.PopupAnimation);
		// 使用系统动画
		mPopupWindow.setAnimationStyle(android.R.style.Animation_Dialog);
		mPopupWindow.update();
		mPopupWindow.setTouchable(true);
		mPopupWindow.setFocusable(true);
	}
}
